package com.turman.blibrary.log;

/**
 * 堆栈信息裁剪工具类
 *
 * @author buobao
 * @since 2024/2/27 17:07
 */
public class BStackTraceUtil {
    //获取裁剪后的栈
    public static StackTraceElement[] getCorppedRealStackTrace(StackTraceElement[] callStack,String ignorePackageName,int maxDepth) {
        return getRealStackTrace(cropStackTrace(callStack,maxDepth),ignorePackageName);
    }

    //获取需要答应的栈，这里去除Blog中的栈（无需展示）
    private static StackTraceElement[] getRealStackTrace(StackTraceElement[] callStack, String ignorePackageName) {
        int ignoreDepth = 0;
        int allDepth = callStack.length;

        for (int i = 0; i < callStack.length; i++) {
            if (ignorePackageName!=null && callStack[i].getClassName().startsWith(ignorePackageName)) {
                ignoreDepth++;
            } else {
                break;
            }
        }
        int realDepth = allDepth - ignoreDepth;
        StackTraceElement[] realStack = new StackTraceElement[realDepth];
        System.arraycopy(callStack,ignoreDepth,realStack,0,realDepth);
        return realStack;
    }

    //裁剪堆栈信息长度，获取需要的堆栈,依据实际栈长度和Blog配置的显示栈长度裁剪
    private static StackTraceElement[] cropStackTrace(StackTraceElement[] callStack, int maxDepth) {
        int realDepth = callStack.length;
        if (maxDepth > 0) {
            realDepth = Math.min(realDepth, maxDepth);
        }

        StackTraceElement[] realStack = new StackTraceElement[realDepth];
        System.arraycopy(callStack, 0, realStack, 0, realDepth);
        return realStack;
    }


}
